package hu.szyrt.bug;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import hu.szyrt.bug.adapters.CategoryWidgetAdapter;
import hu.szyrt.bug.adapters.HighlightsAdapter;
import hu.szyrt.bug.adapters.PlacesListAdapter;
import hu.szyrt.bug.adapters.SubCategoryListAdapter;
import hu.szyrt.bug.animations.ResizeAnimation;
import hu.szyrt.bug.db.DBHandler;
import hu.szyrt.bug.models.PlaceItemBase;
import hu.szyrt.bug.models.Category;
import hu.szyrt.bug.models.SubCategory;
import hu.szyrt.bug.pageindicators.CirclePageIndicator;
import hu.szyrt.bug.utils.Assets;
import hu.szyrt.bug.utils.Utils;
import hu.szyrt.bug.views.SearchEditText;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class CategoryActivity extends Activity {

	// DB
	DBHandler dbHandler;
	Assets assets;
	
	// ViewFlipper -------------------------------
	ViewFlipper viewFlipper;	
	Animation 	animationForwardIN, animationForwardOUT,
	  			animationBackIN, animationBackOUT,
	  			animationUpIN, animationUpOUT,
	  			animationDownIN, animationDownOUT;
	
	private final static int DISPLAY_DEFAULT 		= 0,
							 DISPLAY_HIGHLIGHTS 	= 1,
							 DISPLAY_SUB_CATEGORY	= 2,
							 DISPLAY_PLACES_LIST	= 3,
							 DISPLAY_DESCRIPTION	= 4;
	
	// Category --------------------------------		
	//String[] urbanGuideTexts;
	GridView urbanGuide;
	CategoryWidgetAdapter urbanGuideAdapter;
	
	// Highlights ------------------------------
	View categoryHighlights;
	ViewPager viewPagerHightlights;
	HighlightsAdapter viewPagerHightlightsAdapter;
	CirclePageIndicator indicatorHightlights;
	
	// subCategories ---------------------------
	View subCategoryList;
	ListView subCategoryListView;
	Category currentSubCategory;
	SubCategoryListAdapter subCategoryListAdapter;
	EditText subCategorySearch;
	
	// PlacesList ------------------------------
	View placesList;
	ListView placesListView;
	PlacesListAdapter placesListAdapter;
	SearchEditText placesSearch;
	ResizeAnimation animationSearchGrowing, animationSearchReduce;
	TextView placesHeaderDescriptiontextView;
	
	// Description -----------------------------
	View descriptionView;
	TextView descriptionTextView;
	
	
	private boolean isShowPlacesBySubCategory = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {	
		super.onCreate(savedInstanceState);
		setContentView(R.layout.category);
		
		dbHandler = new DBHandler(this);
		assets = new Assets(this);
		
		viewFlipper = (ViewFlipper)findViewById(R.id.viewFlipper);
		
		// Animációk --------------------------------------
		// Vizszintes: Jobbra, balra
		animationForwardIN = AnimationUtils.loadAnimation(this, R.anim.push_left_in);	// új belépő
		animationForwardOUT = AnimationUtils.loadAnimation(this, R.anim.push_left_out); // régi kilépő
		animationBackIN = AnimationUtils.loadAnimation(this, R.anim.push_right_in);     // új belépő
		animationBackOUT = AnimationUtils.loadAnimation(this, R.anim.push_right_out);	// régi kilépő		
		// Föggőleges: Fel, le
		animationUpIN = AnimationUtils.loadAnimation(this, R.anim.push_up_in);		// új belépő
		animationUpOUT = AnimationUtils.loadAnimation(this, R.anim.push_up_out);		// régi kilépő
		animationDownIN = AnimationUtils.loadAnimation(this, R.anim.push_down_in);		// új belépő
		animationDownOUT = AnimationUtils.loadAnimation(this, R.anim.push_down_out);		// régi kilépő
		 
		
		// Caetgory ----------------------		
		urbanGuideAdapter = new CategoryWidgetAdapter(assets, dbHandler.loadCategories());		
		urbanGuide = (GridView) findViewById(R.id.categoryMain);
		urbanGuide.setAdapter(urbanGuideAdapter);
		urbanGuide.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> a, View v, int i, long l) {
				Category category = (Category)urbanGuideAdapter.getItem(i);
				if(category != null){
					if(category.getImageName().equals("highlights.png")) 
						showHighlights(category); 
					else if(category.hasSubCategroy())
						showSubCategory(category);
					else
						showPlaces(category, false);
				}
			}
		});
		
		
		// Hightlights ---------------------
		categoryHighlights = findViewById(R.id.categoryHighlights);
		viewPagerHightlights = (ViewPager)categoryHighlights.findViewById(R.id.pager);
		indicatorHightlights = (CirclePageIndicator)categoryHighlights.findViewById(R.id.indicator);
		
		
		// SubCategoies --------------------		
		subCategoryList = findViewById(R.id.subCategoryList);	
		subCategoryListView = (ListView)subCategoryList.findViewById(R.id.listView);
		subCategoryListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> a, View v, int i, long l) {
				SubCategory category = (SubCategory)subCategoryListAdapter.getItem(i);
				if(category != null){
					if(currentSubCategory != null && currentSubCategory.getImageName().equals("welcome.png"))
						showDescription(category);
					else
						showPlaces(category, true);
				}
			}
		});
	
		subCategorySearch = (EditText) subCategoryList.findViewById(R.id.search);
		subCategorySearch.setVisibility(View.GONE);
		
		
		// Places List ---------------------		
		placesList = findViewById(R.id.placesList);
		placesSearch = (SearchEditText) placesList.findViewById(R.id.search);
		placesListView = (ListView) placesList.findViewById(R.id.listView);
		placesListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> a, View v, int i, long l) {
				PlaceItemBase pib = (PlaceItemBase)placesListView.getItemAtPosition(i);
				if(pib != null) showPlace(pib);
			}
		});
		placesListView.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				placesSearch.clearFocus();
				return false;
			}
		});
		
		
		// Descrpiton ----------------------
		descriptionView = findViewById(R.id.descriptionView);
		descriptionTextView = (TextView) descriptionView.findViewById(R.id.description);
		
		//animationSearchGrowing = new ResizeAnimation(placesSearch, Utils.getDPSizeByScreenSize(180, 200, 250, 300, getResources()), placesSearch.getLayoutParams().height);
		//animationSearchReduce = new ResizeAnimation(placesSearch, Utils.getDPSize(75, getResources()), placesSearch.getLayoutParams().height);		
		
	}
	
	// Lapozások kezelése ----------------------------------------
	// 1. Highlights
	private void showHighlights(Category category){
		if(viewPagerHightlightsAdapter == null){
			viewPagerHightlightsAdapter = new HighlightsAdapter(assets, new String[]{
					"highlights_1", 
					"highlights_2",
					"highlights_3",
					"highlights_4",
					"highlights_5"
			});
			viewPagerHightlights.setAdapter(viewPagerHightlightsAdapter);			
			indicatorHightlights.setViewPager(viewPagerHightlights);
		}
		
		Button backButton = (Button)categoryHighlights.findViewById(R.id.backButton);
			   backButton.setText(category.getName());
			   backButton.setOnClickListener(backButtonClickListener);
		
		viewFlipper.setInAnimation(animationDownIN);
		viewFlipper.setOutAnimation(animationDownOUT);
		viewFlipper.setDisplayedChild(DISPLAY_HIGHLIGHTS);
	}
	private void hideHighlights(){
		viewFlipper.setInAnimation(animationUpIN);
		viewFlipper.setOutAnimation(animationUpOUT);
		viewFlipper.setDisplayedChild(DISPLAY_DEFAULT);
	}
	
	// 2. SubCategory
	private void showSubCategory(Category category){
		this.currentSubCategory = category;
		
		List<SubCategory> subCategories = dbHandler.loadSubCategories(category);
		if(subCategoryListAdapter == null){
			subCategoryListAdapter = new SubCategoryListAdapter(assets, subCategories);
			subCategoryListView.setAdapter(subCategoryListAdapter);
		}else{
			subCategoryListAdapter.changeList(subCategories);
		}
		subCategoryListView.setSelectionFromTop(0, 0);
		
		Button backButton = (Button)subCategoryList.findViewById(R.id.backButton);
			   backButton.setText(category.getName());
			   backButton.setOnClickListener(backButtonClickListener);
			  
		viewFlipper.setInAnimation(animationUpIN);
		viewFlipper.setOutAnimation(animationUpOUT);
		viewFlipper.setDisplayedChild(DISPLAY_SUB_CATEGORY);
	}
	private void hideSubCategory(){
		Utils.hideKeyboard(placesSearch);
		viewFlipper.setInAnimation(animationDownIN);
		viewFlipper.setOutAnimation(animationDownOUT);
		viewFlipper.setDisplayedChild(DISPLAY_DEFAULT);
	}
	
	// 3. Places
	TextWatcher placeSearchTextWatcher;
	Timer timer = new Timer();
	private void showPlaces(final Category category, final boolean bySubCategory){	
		this.isShowPlacesBySubCategory = bySubCategory;
		// Helyek listája
		List<PlaceItemBase> places = dbHandler.loadPlaces(category, bySubCategory, null);		
		if(placesListAdapter == null){
			placesHeaderDescriptiontextView = (TextView) View.inflate(this, R.layout.category_list_header, null);
			placesHeaderDescriptiontextView.setVisibility(View.GONE);
			placesListView.addHeaderView(placesHeaderDescriptiontextView);
			placesListAdapter = new PlacesListAdapter(assets, places);			
			placesListView.setAdapter(placesListAdapter);
		}else{
			placesListAdapter.setTerms(null);
			placesListAdapter.changeList(places);
		}
		placesListView.setSelectionFromTop(0, 0);
		
		// Leírás
		if(bySubCategory){			
			placesHeaderDescriptiontextView.setText(category.getDescription());
			placesHeaderDescriptiontextView.setVisibility(View.VISIBLE);
			placesHeaderDescriptiontextView.setMaxHeight(Integer.MAX_VALUE); 
		}else{
			placesHeaderDescriptiontextView.setVisibility(View.GONE);
			placesHeaderDescriptiontextView.setMaxHeight(0); // BUG fixing for GONE behavior
		}
		
		// Kereső mező
		if(placeSearchTextWatcher != null){
			placesSearch.removeTextChangedListener(placeSearchTextWatcher);
			placeSearchTextWatcher = null;
		}
		placeSearchTextWatcher = new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before, int count) {}
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			public void afterTextChanged(Editable s) {
				final String searchTerms = s.toString().trim();
				timer.cancel();
				timer.purge();
				timer = new Timer();
				timer.schedule(new TimerTask() {
					public void run() {
						final List<PlaceItemBase> places = searchTerms.length() > 1 ? 
								dbHandler.loadPlaces(category, bySubCategory, searchTerms) :
								dbHandler.loadPlaces(category, bySubCategory, null);
						runOnUiThread(new Runnable() {
							public void run() {
								placesListAdapter.setTerms(searchTerms.length() > 1 ? searchTerms : null);
								placesListAdapter.changeList(places);
							}
						});
					}
				}, 700);
			}
		};
		placesSearch.setText(null);
		placesSearch.addTextChangedListener(placeSearchTextWatcher);		
		
		// Vissza gomb
		Button backButton = (Button)placesList.findViewById(R.id.backButton);
			   backButton.setText(category.getName());
			   backButton.setOnClickListener(backButtonClickListener);
			   
		if(bySubCategory){
			viewFlipper.setInAnimation(animationForwardIN);
			viewFlipper.setOutAnimation(animationForwardOUT);
		}else{
			viewFlipper.setInAnimation(animationUpIN);
			viewFlipper.setOutAnimation(animationUpOUT);
		}
		viewFlipper.setDisplayedChild(DISPLAY_PLACES_LIST);		
	}
	private void hidePlaces(){		
		Utils.hideKeyboard(placesSearch);
		if(isShowPlacesBySubCategory){
			viewFlipper.setInAnimation(animationBackIN);
			viewFlipper.setOutAnimation(animationBackOUT);
			viewFlipper.setDisplayedChild(DISPLAY_SUB_CATEGORY);
		}else{
			viewFlipper.setInAnimation(animationDownIN);
			viewFlipper.setOutAnimation(animationDownOUT);
			viewFlipper.setDisplayedChild(DISPLAY_DEFAULT);
		}
	}
	
	// 4. Place details
	private void showPlace(PlaceItemBase place){
		PlaceActivity.showPlaceBy(this, PlaceActivity.PLACE_ID, place.getId());
	}

	// 5. Description
	private void showDescription(SubCategory subCategory){
		descriptionTextView.setText(subCategory.getDescription());
		Linkify.addLinks(descriptionTextView, Linkify.WEB_URLS | Linkify.PHONE_NUMBERS | Linkify.EMAIL_ADDRESSES);
	    descriptionTextView.setMovementMethod(LinkMovementMethod.getInstance());
	    descriptionTextView.setGravity(Gravity.LEFT);

		Button backButton = (Button)descriptionView.findViewById(R.id.backButton);
			   backButton.setText(subCategory.getName());
			   backButton.setOnClickListener(backButtonClickListener);
		
		viewFlipper.setInAnimation(animationForwardIN);
		viewFlipper.setOutAnimation(animationForwardOUT);
		viewFlipper.setDisplayedChild(DISPLAY_DESCRIPTION);
	}
	
	private void hideDescription(){
		viewFlipper.setInAnimation(animationBackIN);
		viewFlipper.setOutAnimation(animationBackOUT);
		viewFlipper.setDisplayedChild(DISPLAY_SUB_CATEGORY);
	}
	
	// Back
	public boolean showPrev(){	// lapozás
		if(viewFlipper != null && viewFlipper.getDisplayedChild() > DISPLAY_DEFAULT){
			switch (viewFlipper.getDisplayedChild()) {
				case DISPLAY_HIGHLIGHTS: hideHighlights();  return true;				
				case DISPLAY_SUB_CATEGORY: hideSubCategory(); return true;
				case DISPLAY_PLACES_LIST: hidePlaces(); return true;		
				case DISPLAY_DESCRIPTION: hideDescription(); return true;
				default: return false;
			}			
		}
		return false;
	}
	
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			return showPrev();
		}else return super.onKeyUp(keyCode, event);
	}
	
	private OnClickListener backButtonClickListener = new OnClickListener() {
		public void onClick(View v) {
			showPrev();
		}
	};
	
}
